package com.xywy.tangandroid.activity;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.xywy.tangandroid.R;
import com.xywy.tangandroid.adapter.FoodSetTimeAdapter;
import com.xywy.tangandroid.adapter.FoodSetTimeAdapter.setText;
import com.xywy.tangandroid.base.BaseActivity;
import com.xywy.tangandroid.bean.BloodData;
import com.xywy.tangandroid.bean.SendBloodData;
import com.xywy.tangandroid.bean.User;
import com.xywy.tangandroid.greendao.BaseDao;
import com.xywy.tangandroid.greendao.BloodDataDao;
import com.xywy.tangandroid.greendao.DaoMaster;
import com.xywy.tangandroid.greendao.DaoSession;
import com.xywy.tangandroid.util.Constant;
import com.xywy.tangandroid.util.DateUtil;
import com.xywy.tangandroid.util.DeviceUtil;
import com.xywy.tangandroid.util.LogUtil;
import com.xywy.tangandroid.util.UIUtil;
import com.xywy.tangandroid.vollery.OnVolleyResponseListener;
import com.xywy.tangandroid.vollery.PostRequest;

import de.greenrobot.dao.query.QueryBuilder;

public class HandUploadAct extends BaseActivity {
	private RelativeLayout left_img;
	private TextView middle_title;
	private RelativeLayout save_button;
	private TextView time_period;
	private TextView data;
	private TextView time;
	private EditText device_name;
	private EditText measure_blood_text;

	private FoodSetTimeAdapter adapter1;
	private PopupWindow window;
	private int width;
	private int height;
	private RelativeLayout time_period_rel;
	private Long times;

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.act_hand_upload);
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText(getResources().getString(R.string.hand_hold));

		data = (TextView) findViewById(R.id.data);
		time = (TextView) findViewById(R.id.time);

		time_period_rel = (RelativeLayout) findViewById(R.id.time_period_rel);
		time_period = (TextView) findViewById(R.id.time_period);
		device_name = (EditText) findViewById(R.id.device_name);
		measure_blood_text = (EditText) findViewById(R.id.measure_blood_text);

		save_button = (RelativeLayout) findViewById(R.id.save_button);

		adapter1 = new FoodSetTimeAdapter(context, Constant.Testslot);
		initPopWindow();
		initDao();
		Calendar current_calendar = Calendar.getInstance();
		birthDayStr = current_calendar.get(Calendar.YEAR) + "-"
				+ (current_calendar.get(Calendar.MONTH) + 1) + "-"
				+ current_calendar.get(Calendar.DAY_OF_MONTH);
		data.setOnClickListener(this);
		time.setOnClickListener(this);

	}

	/* 初始化GreenDao */
	private SQLiteDatabase db;
	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private BloodDataDao bloodDataDao;
	private SharedPreferences sp;

	private void initDao() {
		// DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
		// null);
		// db = helper.getWritableDatabase();
		// daoMaster = new DaoMaster(db);
		// daoSession = daoMaster.newSession();
		BaseDao basedao = BaseDao.getInstance(this);
		bloodDataDao = basedao.getBloodDataDao();

	}

	@Override
	protected void initListener() {
		left_img.setOnClickListener(this);
		save_button.setOnClickListener(this);
		time_period_rel.setOnClickListener(this);

		adapter1.setView(new setText() {

			@Override
			public TextView setText() {
				return time_period;
			}

			@Override
			public PopupWindow dismisspoppwindow() {
				return window;
			}
		});
	}

	@Override
	protected void initData() {
		times = System.currentTimeMillis() / 1000;
		data.setText(DateUtil.getData(times + ""));
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		if (minute < 10) {
			time.setText(hour + ":0" + minute);
		} else {
			time.setText(hour + ":" + minute);
		}
		// time.setText(hour+":"+minute);
		System.out.println("********" + DateUtil.getHourAndMinute(times + ""));

		sp = context.getSharedPreferences("devicename", Activity.MODE_PRIVATE);
		device_name.setText(sp.getString("save_devicename", ""));
	}

	/**
	 * 手动上传数据
	 */
	private void sendHandBloodData() {
		PostRequest<String> request = new PostRequest<String>(
				Constant.blood_url, String.class,
				new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						UIUtil.DissDialog(context, waittingDialog);
						LogUtil.i("VolleyError", volleyError + "");
						showToast("上传失败,请重试");
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(context, waittingDialog);
						System.out.println("获取的json的数据....." + response);
						JSONObject object;
						try {
							object = new JSONObject(response);
							int status = object.getInt("status");
							String msgs = object.getString("msg");
							if (status == 0) {
								UIUtil.showToast(context,
										getString(R.string.send_sucess));
								// TODO : 请求成功后保存当前数据入库。
								System.out.println("kaishi  ----save");
								insertData();
								finish();
							} else {
								UIUtil.showToast(context, msgs);
								showToast("上传失败,请重试");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

				});

		HashMap<String, String> params = new HashMap<String, String>();
		params.put("sn", Constant.getBloodSign(BloodData1(), context));
		params.put("app_username", "xywy_xuetang");

		// params.put("app_username", "xywy_xuetang");
		long timess = getTimstamp(data.getText().toString() + " "
				+ time.getText().toString());
		long curr = System.currentTimeMillis() / 1000;
		if (timess > curr) {
			showToast("录入时间不能大于当前时间");
			return;
		}
		params.put("xywy_userid", User.getIUserInstance(this).getUserid());
		System.out.println("时间戳 " + timess);
		params.put("recordtime", timess + "");
		params.put("sort", "xuetang");
		params.put("data", BloodData1());
		request.setParams(params);
		request.setIsParseJson(false);
		executeRequest(request);
	}

	/*
	 * 8 保存数据到数据库
	 */
	private void insertData() {
		BloodData data = new BloodData();
		data.setApp_data("temp_automactily_device_identify");
		data.setCandyvalue(measure_blood_text.getText().toString().trim());
		data.setId(null);
		data.setInputed_device_str(device_name.getText().toString().trim());
		data.setPeriod(time_period.getText().toString().trim());
		long timess = getTimstamp(this.data.getText().toString() + " "
				+ time.getText().toString());
		data.setRecordtime(timess + "");
		data.setShou_data(measure_blood_text.getText().toString().trim());
		System.out.println(bloodDataDao.insert(data));

		QueryBuilder<BloodData> qb = bloodDataDao.queryBuilder();
		List<BloodData> blood_datas = qb.list();
		for (BloodData data1 : blood_datas) {
			System.out.println(data1.getCandyvalue());
		}

	}

	private String BloodData1() {
		SendBloodData data = new SendBloodData();
		data.setApp_data("temp_automactily_device_identify");
		data.setApp_user_id("3");
		data.setApp_username("xywy_xuetang");
		data.setXywy_userid(User.getIUserInstance(context).getUserid());
		data.setSort("xuetang");
		data.setShou_data(measure_blood_text.getText().toString().trim());
		data.setCandyvalue(measure_blood_text.getText().toString().trim());
		data.setRecordtime(times + "");
		data.setPeriod(time_period.getText().toString().trim());
		data.setInputed_device_str(device_name.getText().toString().trim());
		data.setDevice_id("temp_bloodcandy_device_id");
		data.setHand_str("temp_bloodcandy_hand_str");

		Gson gson = new Gson();
		return "[" + gson.toJson(data) + "]";
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.left_img:
			finish();
			break;
		case R.id.save_button:
			if (measure_blood_text.getText().length() == 0) {
				Toast.makeText(context, "测量值值不能为空！", Toast.LENGTH_SHORT).show();
				return;

			}
			if (checkDataIsEmpty()) {
				sendHandBloodData();
				sp.edit()
						.putString("save_devicename",
								device_name.getText().toString().trim())
						.commit();
			}
			break;
		case R.id.time_period_rel:

			if (Constant.flag_blood == true) {
				showPopWindow();
			} else {
				if (window.isShowing()) {
					window.dismiss();
					Constant.flag_blood = true;
				} else {
					showPopWindow();
				}
			}
			break;
		case R.id.data:
			showDateDialog();
			break;
		case R.id.time:
			showTimeDialog();
			break;
		default:
			break;
		}
	}

	private String birthDayStr;

	private void showDateDialog() {
		// String dateStr = User.getIUserInstance().getBirthday();
		// String dateTemp[] = dateStr.split("-");
		// int year = Integer.parseInt(dateTemp[0]);
		// int mounth = Integer.parseInt(dateTemp[1]);
		// int day = Integer.parseInt(dateTemp[2]);
		Calendar current_calendar = Calendar.getInstance();
		final DatePickerDialog dp = new DatePickerDialog(this,
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker dp, int year, int mounth,
							int day) {
						// TODO Auto-generated method stub
						birthDayStr = year + "-" + (mounth + 1) + "-" + day;
						data.setText(birthDayStr);
					}
				}, current_calendar.get(Calendar.YEAR),
				current_calendar.get(Calendar.MONTH) + 1,
				current_calendar.get(Calendar.DAY_OF_MONTH));
		long currentDate = System.currentTimeMillis();
		dp.getDatePicker().setMaxDate(currentDate);
		Calendar calendar = Calendar.getInstance();
		Calendar calendar1 = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 1940);
		long minDate = calendar.getTimeInMillis();
		dp.getDatePicker().setMinDate(minDate);
		dp.getDatePicker().setMaxDate(System.currentTimeMillis());
		dp.show();
	}

	private void showTimeDialog() {
		Calendar current_calendar = Calendar.getInstance();
		;
		TimePickerDialog tp = new TimePickerDialog(this,
				new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker arg0, int hour, int minute) {
						String strh;
						if (hour < 10) {
							strh = "0" + hour + "";
						} else {
							strh = hour + "";
						}

						String strt;
						if (minute < 10) {
							strt = "0" + minute + "";
						} else {
							strt = minute + "";
						}
						String str = strh + ":" + strt;
						time.setText(str);
					}
				}, current_calendar.get(Calendar.HOUR_OF_DAY), current_calendar
						.get(Calendar.MINUTE), true);
		tp.show();
	}

	private boolean checkDataIsEmpty() {

		if ("请点击选择".equals(time_period.getText().toString().trim())) {
			UIUtil.showToast(context, "请点击时间段");
			return false;
		}
		if (device_name.length() <= 0) {
			UIUtil.showToast(context, "设备名不能为空");
			return false;
		}

		String sugar_data = measure_blood_text.getText().toString().toString();
		int sugar = Integer.parseInt(sugar_data);
		if (sugar_data.length() <= 0) {
			UIUtil.showToast(context, "血糖数值不能为空");
			return false;
		} else if (sugar < 2 || sugar > 11) {

			Toast.makeText(context, "请输入2.0~11.0 测量值", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		// if(!Pattern.matches(Constant.NUMBER, sugar_data)){
		// UIUtil.showToast(context, "请您输入数字");
		// return false;
		// }
		if (Double.valueOf(sugar_data) < 2 || Double.valueOf(sugar_data) > 15) {
			UIUtil.showToast(context, "您输入的血糖数值错误");
			measure_blood_text.setText("");
			return false;
		}
		return true;
	}

	/**
	 * 初始化 popwindow
	 */
	private void initPopWindow() {
		View popupView = this.getLayoutInflater().inflate(
				R.layout.popwindow_item, null);
		ListView lv = (ListView) popupView.findViewById(R.id.pop_listview);
		lv.setAdapter(adapter1);

		width = DeviceUtil.getDeviceWidth(HandUploadAct.this) / 2;
		window = new PopupWindow(popupView, width, 300);
		window.setTouchable(true);
		window.setBackgroundDrawable(new BitmapDrawable());
		window.setOutsideTouchable(true);
	}

	private void showPopWindow() {
		window.showAsDropDown(time_period);
		Constant.flag_blood = false;
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (window != null && window.isShowing()) {
			window.dismiss();
			Constant.flag_blood = true;
		}
	}

	private long getTimstamp(String birthDayStr) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date date = sdf.parse(birthDayStr);
			return date.getTime() / 1000;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
}
